/**
 * 下载模块
 * 负责WGT包的下载、重试、进度管理
 */

class DownloadManager {
  /**
   * 下载WGT包（带重试）
   * @param {String} downloadUrl - 下载地址
   * @param {Function} onProgress - 进度回调
   * @returns {String} 下载的文件路径
   */
  async downloadZip(downloadUrl, onProgress) {
    console.log('=== downloadZip 方法调用 ===')
    console.log('下载URL:', downloadUrl)
    console.log('URL类型:', typeof downloadUrl)
    console.log('URL是否为空:', !downloadUrl)
    
    if (!downloadUrl) {
      throw new Error('下载URL为空')
    }
    
    const maxRetries = 3
    let lastError = null
    
    // 尝试主要下载地址
    for (let i = 0; i < maxRetries; i++) {
      try {
        console.log(`第 ${i + 1} 次尝试下载...`)
        
        if (onProgress) {
          onProgress({
            stage: 'download',
            progress: 0,
            message: `开始下载... (${i + 1}/${maxRetries})`
          })
        }
        
        const tempFilePath = await this.tryDownload(downloadUrl, onProgress)
        console.log('下载成功，返回临时文件路径:', tempFilePath)
        return tempFilePath
      } catch (error) {
        console.error(`第 ${i + 1} 次下载失败:`, error)
        lastError = error
        
        // 如果不是最后一次重试，等待后重试
        if (i < maxRetries - 1) {
          console.log(`等待 ${(i + 1) * 2} 秒后重试...`)
          await new Promise(resolve => setTimeout(resolve, (i + 1) * 2000))
        }
      }
    }
    
    // 如果主要地址都失败，尝试备用地址
    console.log('主要下载地址全部失败，尝试备用地址...')
    const fallbackUrl = this.getFallbackDownloadUrl(downloadUrl)
    
    if (fallbackUrl) {
      try {
        console.log('尝试备用下载地址:', fallbackUrl)
        
        if (onProgress) {
          onProgress({
            stage: 'download',
            progress: 0,
            message: '使用备用地址下载...'
          })
        }
        
        return await this.tryDownload(fallbackUrl, onProgress)
      } catch (error) {
        console.error('备用地址下载也失败:', error)
      }
    }
    
    throw new Error(`下载失败，已重试 ${maxRetries} 次: ${lastError.message}`)
  }

  /**
   * 尝试下载（单次）
   */
  async tryDownload(downloadUrl, onProgress) {
    return new Promise((resolve, reject) => {
      console.log('=== tryDownload 开始 ===')
      console.log('下载地址:', downloadUrl)
      
      const downloadTask = uni.downloadFile({
        url: downloadUrl,
        success: (res) => {
          console.log('下载响应状态:', res.statusCode)
          if (res.statusCode === 200) {
            console.log('下载成功，临时文件路径:', res.tempFilePath)
            resolve(res.tempFilePath)
          } else {
            reject(new Error(`下载失败，状态码: ${res.statusCode}`))
          }
        },
        fail: (error) => {
          reject(new Error(`下载失败: ${error.errMsg || error.message}`))
        }
      })

      // 监听下载进度
      if (onProgress) {
        downloadTask.onProgressUpdate((progress) => {
          onProgress({
            stage: 'download',
            progress: progress.progress,
            message: `下载中... ${progress.progress}%`,
            totalBytesExpectedToWrite: progress.totalBytesExpectedToWrite,
            totalBytesWritten: progress.totalBytesWritten
          })
        })
      }
    })
  }

  /**
   * 获取备用下载地址
   */
  getFallbackDownloadUrl(originalUrl) {
    if (originalUrl.includes('gitee.com') && originalUrl.includes('/raw/')) {
      const match = originalUrl.match(/gitee\.com\/([^\/]+)\/([^\/]+)\/raw\/([^\/]+)\/(.+)/)
      if (match) {
        const [, owner, repo, branch, filePath] = match
        // 备用方案: 使用Gitee的blob链接
        const blobUrl = `https://gitee.com/${owner}/${repo}/blob/${branch}/${filePath}?raw=true`
        console.log('备用下载地址(blob):', blobUrl)
        return blobUrl
      }
    }
    return null
  }
}

export default new DownloadManager() 